package cc.lucien.jpa.controller;

import cc.lucien.jpa.entity.User;
import cc.lucien.jpa.repository.JpaUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lucien-ma
 * @date 2021/9/14
 * @apiNote
 */
@RestController("jpaHandler")
@RequestMapping("/jpauser")
public class UserHandler {

    @Autowired
    private JpaUserRepository jpaUserRepository;

    @GetMapping("/findAll")
    public List<User> findAll() {
        return jpaUserRepository.findAll();
    }

    @GetMapping("/findById/{id}")
    public User findById(@PathVariable("id") Integer id) {
        return jpaUserRepository.findById(id).get();
    }

    @PostMapping("/save")
    public void save(@RequestBody User user) {
        jpaUserRepository.save(user);
    }

    @PutMapping("/update")
    public void update(@RequestBody User user) {
        // Spring Data JPA 中 save 和 update 合并成了一个方法
        // 没有就添加，有就修改
        jpaUserRepository.save(user);
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") Integer id) {
        jpaUserRepository.deleteById(id);
    }

    @GetMapping("/findByUserName/{username}")
    public User findByUserName(@PathVariable("username") String userName) {
        return jpaUserRepository.findByUsername(userName);
    }
}
